<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">抄表录入</h1>
      <div class="header-controls">
        <!-- 搜索和操作按钮区域 -->
      </div>
    </div>

    <!-- 功能说明 -->
    <div class="function-description">
      <p>
        功能说明:抄表单需分月进行导入,导入或添加抄表数据后,立即生成相应的未缴费用账单,使用键盘左右键可以浏览更多数据。
      </p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        录入数据
      </el-button>
      <el-button type="success" @click="exportData">
        <el-icon><Download /></el-icon>
        导出抄表数据
      </el-button>
      <el-button type="success" @click="showImportDialog">
        <el-icon><Upload /></el-icon>
        导入抄表数据
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        删除
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchParams.name"
        placeholder="小区/房号/收费项目/收费标准"
        class="search-input"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button @click="handleFilter">
        <el-icon><Filter /></el-icon>
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="cellName" label="小区" width="120" />
        <el-table-column prop="houseNum" label="房号" width="120" />
        <el-table-column
          prop="chargestandardName"
          label="收费标准"
          width="120"
        />
        <el-table-column prop="currentMonth" label="月份" width="80">
          <template #default="{ row }"> {{ row.currentMonth }}月 </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="80" />
        <el-table-column prop="startingDegree" label="起度" width="80" />
        <el-table-column prop="endDegree" label="止度" width="80" />
        <el-table-column prop="magnification" label="倍率" width="80" />
        <el-table-column label="用量" width="80">
          <template #default="{ row }">
            {{ calculateUsage(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="录入抄表数据"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="小区" prop="cellId">
          <el-select
            v-model="formData.cellId"
            placeholder="请选择小区"
            style="width: 100%"
            :loading="loadingOptions.cell"
            @change="handleCellChange"
          >
            <el-option
              v-for="cell in cellList"
              :key="cell.id"
              :label="cell.name"
              :value="cell.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑类型" prop="buildingTypeId">
          <el-select
            v-model="formData.buildingTypeId"
            placeholder="请选择建筑类型"
            style="width: 100%"
            :loading="loadingOptions.buildingType"
            :disabled="!formData.cellId"
            @change="handleBuildingTypeChange"
          >
            <el-option
              v-for="buildingType in buildingTypeList"
              :key="buildingType.id"
              :label="buildingType.name"
              :value="buildingType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="建筑" prop="buildingId">
          <el-select
            v-model="formData.buildingId"
            placeholder="请选择建筑"
            style="width: 100%"
            :loading="loadingOptions.building"
            :disabled="!formData.buildingTypeId"
            @change="handleBuildingChange"
          >
            <el-option
              v-for="building in buildingList"
              :key="building.id"
              :label="building.name"
              :value="building.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房屋" prop="houseId">
          <el-select
            v-model="formData.houseId"
            placeholder="请选择房屋"
            style="width: 100%"
            :loading="loadingOptions.house"
            :disabled="!formData.buildingId"
            filterable
            remote
            :remote-method="searchHouses"
            clearable
          >
            <el-option
              v-for="house in filteredHouseList"
              :key="house.roomId"
              :label="`${house.unit}${house.floor}${house.room}室`"
              :value="house.roomId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收费标准" prop="chargestandardId">
          <el-select
            v-model="formData.chargestandardId"
            placeholder="请选择收费标准"
            style="width: 100%"
            :loading="loadingOptions.chargeStandard"
          >
            <el-option
              v-for="standard in chargeStandardList"
              :key="standard.id"
              :label="`${standard.name} - ${standard.pricestr}`"
              :value="standard.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="currentMonth">
          <el-select
            v-model="formData.currentMonth"
            placeholder="请选择月份"
            style="width: 100%"
          >
            <el-option
              v-for="month in 12"
              :key="month"
              :label="`${month}月`"
              :value="month"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="起度" prop="startingDegree">
          <el-input-number
            v-model="formData.startingDegree"
            :precision="2"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="止度" prop="endDegree">
          <el-input-number
            v-model="formData.endDegree"
            :precision="2"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="倍率" prop="magnification">
          <el-input-number
            v-model="formData.magnification"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入抄表数据对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入抄表数据"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-dialog-content">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传.xlsx/.xls文件，且文件大小不超过10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <p>1. 请按照模板格式填写数据</p>
          <p>2. 月份请填写数字（1-12）</p>
          <p>3. 起度、止度、倍率请填写数字</p>
          <p>4. 确保必填字段都已填写完整</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button @click="handleDownloadTemplate">下载模板</el-button>
          <el-button
            type="primary"
            :loading="importLoading"
            @click="handleImport"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, type FormInstance } from "element-plus";
import {
  Plus,
  Download,
  Upload,
  Delete,
  Search,
  Filter
} from "@element-plus/icons-vue";
import {
  getMeterReadingList,
  addMeterReading,
  deleteMeterReading,
  importMeterReading,
  exportMeterReading,
  type MeterReadingItem,
  type MeterReadingQueryParams,
  type MeterReadingAddParams
} from "@/api/meterReading";
import { findAllCells, type Cell } from "@/api/cell";
import {
  getBuildingTypeList,
  getBuildingList,
  getHouseManagement,
  type BuildingType,
  type BuildingItem,
  type HouseItem
} from "@/api/building";
import {
  getChargeStandardListByChargeTypeName,
  type ChargeStandardItem
} from "@/api/chargeStandard";

defineOptions({ name: "MeterReading" });

// 响应式数据
const loading = ref(false);
const tableData = ref<MeterReadingItem[]>([]);
const selectedRows = ref<MeterReadingItem[]>([]);
const showAddDialog = ref(false);
// 已去除编辑模式

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const selectedFile = ref<File | null>(null);
const uploadRef = ref();

// 级联选择相关数据
const cellList = ref<Cell[]>([]);
const buildingTypeList = ref<BuildingType[]>([]);
const buildingList = ref<BuildingItem[]>([]);
const houseList = ref<HouseItem[]>([]);
const filteredHouseList = ref<HouseItem[]>([]);
const chargeStandardList = ref<ChargeStandardItem[]>([]);
const loadingOptions = ref({
  cell: false,
  buildingType: false,
  building: false,
  house: false,
  chargeStandard: false
});

// 搜索参数
const searchParams = reactive<MeterReadingQueryParams>({
  page: 0,
  limit: 10,
  name: ""
});

// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 表单数据
const formData = reactive<MeterReadingAddParams>({
  cellId: undefined,
  buildingTypeId: undefined,
  buildingId: undefined,
  houseId: undefined,
  chargestandardId: undefined,
  currentMonth: 1,
  startingDegree: 0,
  endDegree: 0,
  magnification: 1
});

// 表单验证规则
const formRules = {
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  buildingTypeId: [
    { required: true, message: "请选择建筑类型", trigger: "change" }
  ],
  buildingId: [{ required: true, message: "请选择建筑", trigger: "change" }],
  houseId: [{ required: true, message: "请选择房屋", trigger: "change" }],
  chargestandardId: [
    { required: true, message: "请选择收费标准", trigger: "change" }
  ],
  currentMonth: [{ required: true, message: "请选择月份", trigger: "change" }],
  startingDegree: [{ required: true, message: "请输入起度", trigger: "blur" }],
  endDegree: [{ required: true, message: "请输入止度", trigger: "blur" }],
  magnification: [{ required: true, message: "请输入倍率", trigger: "blur" }]
};

const formRef = ref<FormInstance>();

// 计算用量
const calculateUsage = (row: MeterReadingItem) => {
  const usage = (row.endDegree - row.startingDegree) * row.magnification;
  return usage.toFixed(2);
};

// 获取小区列表
const fetchCellList = async () => {
  try {
    loadingOptions.value.cell = true;
    const response = await findAllCells();
    if (response.code === 0 && response.data) {
      cellList.value = response.data;
    }
  } catch (error) {
    console.error("获取小区列表失败:", error);
    ElMessage.error("获取小区列表失败");
  } finally {
    loadingOptions.value.cell = false;
  }
};

// 获取收费标准列表
const fetchChargeStandardList = async () => {
  try {
    loadingOptions.value.chargeStandard = true;
    const response = await getChargeStandardListByChargeTypeName({
      page: 0,
      limit: 0,
      name: "水电费"
    });
    if (response.code === 0 && response.data) {
      chargeStandardList.value = response.data;
    }
  } catch (error) {
    console.error("获取收费标准列表失败:", error);
    ElMessage.error("获取收费标准列表失败");
  } finally {
    loadingOptions.value.chargeStandard = false;
  }
};

// 获取楼栋类型列表
const fetchBuildingTypeList = async (cellId: number) => {
  try {
    loadingOptions.value.buildingType = true;
    const response = await getBuildingTypeList(cellId);
    if (response.code === 0 && response.data) {
      buildingTypeList.value = response.data;
    }
  } catch (error) {
    console.error("获取楼栋类型列表失败:", error);
    ElMessage.error("获取楼栋类型列表失败");
  } finally {
    loadingOptions.value.buildingType = false;
  }
};

// 获取楼栋列表
const fetchBuildingList = async (buildingTypeId: number) => {
  try {
    loadingOptions.value.building = true;
    const response = await getBuildingList(buildingTypeId);
    if (response.code === 0 && response.data) {
      buildingList.value = response.data;
    }
  } catch (error) {
    console.error("获取楼栋列表失败:", error);
    ElMessage.error("获取楼栋列表失败");
  } finally {
    loadingOptions.value.building = false;
  }
};

// 获取房屋列表
const fetchHouseList = async (buildingId: number) => {
  try {
    loadingOptions.value.house = true;
    const response = await getHouseManagement(buildingId);
    if (response.code === 0 && response.data) {
      houseList.value = response.data.roomList;
      filteredHouseList.value = response.data.roomList;
    }
  } catch (error) {
    console.error("获取房屋列表失败:", error);
    ElMessage.error("获取房屋列表失败");
  } finally {
    loadingOptions.value.house = false;
  }
};

// 搜索房屋
const searchHouses = (query: string) => {
  if (!query || query.trim() === "") {
    filteredHouseList.value = houseList.value;
    return;
  }

  const searchTerm = query.toLowerCase().trim();
  filteredHouseList.value = houseList.value.filter(house => {
    const houseText =
      `${house.unit}${house.floor}${house.room}室`.toLowerCase();
    return houseText.includes(searchTerm);
  });
};

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current - 1,
      limit: pagination.size,
      name: searchParams.name
    };
    const response = await getMeterReadingList(params);
    console.log("API响应数据:", response);

    // 根据实际API响应结构处理数据
    if (response && response.data) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0;
    } else {
      tableData.value = [];
      pagination.total = 0;
    }

    console.log("处理后的表格数据:", tableData.value);
    console.log("表格数据长度:", tableData.value.length);
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 筛选
const handleFilter = () => {
  // 这里可以添加更多筛选条件
  handleSearch();
};

// 选择变化
const handleSelectionChange = (selection: MeterReadingItem[]) => {
  selectedRows.value = selection;
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  fetchData();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page;
  fetchData();
};

// 级联选择处理函数
const handleCellChange = async (cellId: number) => {
  // 清空下级选择
  formData.buildingTypeId = undefined;
  formData.buildingId = undefined;
  formData.houseId = undefined;
  buildingTypeList.value = [];
  buildingList.value = [];
  houseList.value = [];

  if (cellId) {
    await fetchBuildingTypeList(cellId);
  }
};

const handleBuildingTypeChange = async (buildingTypeId: number) => {
  // 清空下级选择
  formData.buildingId = undefined;
  formData.houseId = undefined;
  buildingList.value = [];
  houseList.value = [];

  if (buildingTypeId) {
    await fetchBuildingList(buildingTypeId);
  }
};

const handleBuildingChange = async (buildingId: number) => {
  // 清空下级选择
  formData.houseId = undefined;
  houseList.value = [];
  filteredHouseList.value = [];

  if (buildingId) {
    await fetchHouseList(buildingId);
  }
};

// 已去除编辑操作

// 删除单个
const handleDelete = async (row: MeterReadingItem) => {
  try {
    await ElMessageBox.confirm("确定要删除这条数据吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    // 注意：这里需要根据实际API调整，因为返回的数据可能没有ID
    if (row.id) {
      await deleteMeterReading({ ids: [row.id] });
      ElMessage.success("删除成功");
      fetchData();
    } else {
      ElMessage.warning("无法删除：缺少数据ID");
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    const ids = selectedRows.value
      .filter(item => item.id)
      .map(item => item.id!);

    if (ids.length === 0) {
      ElMessage.warning("选中的数据缺少ID，无法删除");
      return;
    }

    await deleteMeterReading({ ids });
    ElMessage.success("删除成功");
    fetchData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  selectedFile.value = null;
  // 重置上传组件状态
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 文件选择处理
const handleFileChange = (file: any) => {
  const isExcel = file.name.endsWith(".xlsx") || file.name.endsWith(".xls");
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error("只能上传.xlsx/.xls文件!");
    return false;
  }
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过10MB!");
    return false;
  }

  selectedFile.value = file.raw;
  return true;
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    // 这里可以调用下载模板的API
    ElMessage.success("模板下载成功");
  } catch (error) {
    console.error("下载模板失败:", error);
    ElMessage.error("下载模板失败");
  }
};

// 处理导入
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning("请先选择要导入的文件");
    return;
  }

  importLoading.value = true;
  try {
    await importMeterReading(selectedFile.value);
    ElMessage.success("导入成功");
    importDialogVisible.value = false;
    selectedFile.value = null;
    // 重置上传组件状态
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    // 刷新列表
    await fetchData();
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    importLoading.value = false;
  }
};

// 导出数据
const exportData = async () => {
  try {
    loading.value = true;
    const response = await exportMeterReading();
    // 创建下载链接
    const blob = new Blob([response as BlobPart], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = "抄表数据.xlsx";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    await addMeterReading(formData);
    ElMessage.success("添加成功");
    showAddDialog.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error("添加失败");
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    cellId: undefined,
    buildingTypeId: undefined,
    buildingId: undefined,
    houseId: undefined,
    chargestandardId: undefined,
    currentMonth: 1,
    startingDegree: 0,
    endDegree: 0,
    magnification: 1
  });
  // 清空级联选择数据
  buildingTypeList.value = [];
  buildingList.value = [];
  houseList.value = [];
  filteredHouseList.value = [];
};

// 组件挂载时获取数据
onMounted(() => {
  // 添加一些测试数据来验证页面显示
  tableData.value = [
    {
      id: 8,
      cellName: "周森国际",
      buildingTypeName: "公寓",
      buildingName: "一栋",
      houseNum: "111",
      chargestandardName: "电费",
      unitPrice: 1.5,
      currentMonth: 1,
      startingDegree: 33.45,
      endDegree: 56.93,
      magnification: 1
    },
    {
      id: 9,
      cellName: "周森国际",
      buildingTypeName: "公寓",
      buildingName: "一栋",
      houseNum: "112",
      chargestandardName: "电费",
      unitPrice: 1.5,
      currentMonth: 1,
      startingDegree: 33.67,
      endDegree: 55.78,
      magnification: 1
    }
  ];
  pagination.total = 2;

  // 获取小区列表
  fetchCellList();

  // 获取收费标准列表
  fetchChargeStandardList();

  // 然后尝试获取真实数据
  fetchData();
});
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.function-description {
  background: white;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.function-description p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 20px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.import-tips p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
